import React, { ReactElement, useState, useEffect, useRef, RefObject } from 'react'
import { Modal, Form, Select, FormInstance, message } from 'antd'
import { getAccountRolesRequest, getRoleListRequest, updateAccountRoleRequest } from './ajax'
import { awaitWrap } from '@src/assets/js/tool'
import { RoleShcema } from '@src/components/schema/role'
import { AccountSchema } from '@src/components/schema/account'
const { Item } = Form
const { Option } = Select

async function initAccountRoleList (id: string | undefined, ref: RefObject<FormInstance>): Promise<void> {
  if (id === undefined) {
    return undefined
  }
  const [e, d] = await awaitWrap(getAccountRolesRequest(id))
  if (e === null && d instanceof Array) {
    const ids = d.map(li => li.roleid)
    ref.current?.setFieldsValue({ ids })
  }
}

// 初始化角色列表
async function initRoleList (setRoleList: (v: RoleShcema[]) => void, setRoleMap: (v: RoleMap) => void): Promise<void> {
  const [e, d] = await awaitWrap(getRoleListRequest())
  if (e === null && d instanceof Array) {
    setRoleList(d)
    const r: RoleMap = {}
    d.forEach(li => {
      r[li.id] = li
    })
    setRoleMap(r)
  }
}

async function submitHandle (ids: string[], roleMap: RoleMap, account: AccountSchema | null, hide: () => void): Promise<void> {
  if (account === null || account.id === undefined) {
    await message.error('账号不存在')
    return undefined
  }
  const h = message.loading('提交中', 120)
  const [e] = await awaitWrap(updateAccountRoleRequest(ids, account.id))
  h()
  if (e === null) {
    hide()
    await message.success('更新成功')
  }
}

interface RoleMap {
  [k: string]: RoleShcema
}

interface Props {
  visible: boolean
  hide: () => void
  data: AccountSchema | null
}

function Main ({ visible, hide, data }: Props): ReactElement {
  const ref = useRef<FormInstance>(null)
  const [roles, setRoles] = useState<RoleShcema[]>([])
  const [roleMap, setRoleMap] = useState<RoleMap>({})
  const [roleId, setRoleId] = useState<string>()
  useEffect(() => {
    if (data !== null) {
      initAccountRoleList(data.id, ref).catch(e => console.error(e))
    }
  }, [data])
  useEffect(() => {
    initRoleList(setRoles, setRoleMap).catch(e => console.error(e))
  }, [])
  return (
    <Modal title='绑定角色' visible={visible} maskClosable={false} onCancel={hide} onOk={() => ref.current?.submit()}>
      <Form ref={ref} onFinish={async (d: {ids: string[]}) => await submitHandle(d.ids, roleMap, data, hide)}>
        <Item name='ids' label='添加角色' rules={[{ required: true, message: '角色不能为空' }]}>
          <Select placeholder='请选择' mode='multiple' value={roleId} onChange={v => setRoleId(v)}>
            {roles.map(li => {
              return <Option value={li.id} key={li.id}>{li.name}</Option>
            })}
          </Select>
        </Item>
      </Form>
    </Modal>
  )
}

export default Main
